<?php
namespace frontend\controllers;

use common\models\Code;
use common\models\ReceiveForm;
use Yii;
use yii\helpers\Json;
use yii\web\Controller;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @return string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @author thanatos <thanatos915@163.com>
     */
    public function actionForm()
    {

//        Yii::$app->session->set('wechat_user', Json::decode(file_get_contents('1.txt')));
        $app = Yii::$app->wechat->official;
        // 微信授权
        $oauth = $app->oauth;
        $user = Yii::$app->session->get('wechat_user');
        if (empty($user)){
            Yii::$app->session->set('target_url', Yii::$app->request->url);
            return $oauth->redirect()->send();
        }
        $app = Yii::$app->wechat->payment;
//        $user = Yii::$app->session->get('wechat_user');
//        file_put_contents('1.txt', json_encode($user));
        $config = $app->jssdk->buildConfig(['scanQRCode']);
        return $this->render('form', [
            'config' => $config
        ]);

    }

    public function actionSearch()
    {
        $post = Yii::$app->request->post();
        $key = $post['key'];
        if ($key) {
            $model = Code::findOne(['link' => $key]);
        }

        if ($model) {
            $data = [
                'status' => 'ok',
                'data' => $model->toArray()
            ];
        } else {
            $data = [
                'status' => 'error'
            ];
        }

        return Json::encode($data);

    }

    public function actionReceive()
    {
        $model  = new ReceiveForm();
        if ($model->submit(Yii::$app->request->post())) {
            $data = [
                'status' => 'ok',
            ];
        } else {
            $data = [
                'status' => 'error',
                'msg' => $model->getFirstError('security')
            ];
        }

        return Json::encode($data);

    }

    public function actionOauthCallback()
    {
        $app = Yii::$app->wechat->official;
        $user = $app->oauth->user();
        Yii::$app->session->set('wechat_user', $user->toArray());
        return Yii::$app->response->redirect(Yii::$app->session->get('target_url'))->send();
    }

    public function actionSendSms()
    {
        $mobile = Yii::$app->request->post('mobile');
        $smsModel = Yii::$app->sms;
        $result = $smsModel->send($mobile);
        if ($result) {
            $data = [
                'status' => 'ok'
            ];
        } else {
            $data = [
                'status' => 'error'
            ];
        }
        return Json::encode($data);
    }

}
